﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using HuaCheng.Controller;
using HuaCheng.DataAccess;
using HuaCheng.Model;
using System.Threading;
using HuaCheng.SendAndReceive;
using HuaCheng.CommonClass;

namespace HuaCheng.Views
{
    /// <summary>
    /// 校正因子
    /// </summary>
    public partial class CorrectionFactorPage : Form
    {
        private int caliCIndx;// 通道索引
        FactorName factorName;//因子名称
        private ChannCalibrate curChannelCalibrate;//定义一个当前通道和当前因子类型的对应的校准因子表
        private ChannelCalibrates calibrates = new ChannelCalibrates();//实例化ChannelCalibrates表
        private CalibrateControl calCalibrate = new CalibrateControl();//实例化计算校准方法
        private CalibrateSourceData sourceData1;
        private CalibrateSourceData sourceData2;
        private FactorList factorList=new FactorList(); // 校准因子信息表
        private DataTable calibrateDataDt = new DataTable();//实例化一个校准因子表格
        public static string dev_ip;
        public int GID;//柜号
        public int MID;//中位机号
        public string fileName;
        public CorrectionFactorPage(string ip,int gid,int mid,string filename)
        {
            InitializeComponent();
            dev_ip = ip;
            GID = gid;
            MID = mid;
            fileName = filename;
            BindChl();
        }
        /// <summary>
        /// 退出按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        public void BindChl()
        {
            List<int> chlNum = ChlMapHelper.ChannelNum(dev_ip,GID,MID);
            List<string> strChlNum = new List<string>();
            for (int i = 0; i < chlNum.Count; i++)
            {
                string strChl = "通道" + chlNum[i];
                strChlNum.Add(strChl);
            }
            cbxChlNum.DataSource = strChlNum;
            cbxChlNum.SelectedIndex = -1;
        }
        /// <summary>
        /// 加载按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLoad_Click(object sender, EventArgs e)
        {
            ////显示校正因子
            //CommandProtocol.ReviseFactorProtect ProtectFactor = new CommandProtocol.ReviseFactorProtect();
            ////控制校正因子包
            //CommandProtocol.ResiveFactorControl ControlFactor = new CommandProtocol.ResiveFactorControl();
            //显示校正因子
            CommandProtocol.CurrentReviseFactor CurrentFactor = new CommandProtocol.CurrentReviseFactor();
            //控制校正因子包
            CommandProtocol.VoltageReviseFactor VoltageFactor = new CommandProtocol.VoltageReviseFactor();
            int mapCount = ChannelMapControl.GetDevChlMapLine(dev_ip,GID,MID);//读取每行排列个数
            //ProtectFactor.CID = this.cbxChlNum.SelectedIndex % mapCount;
            //ControlFactor.CID = this.cbxChlNum.SelectedIndex % mapCount;
            //ProtectFactor.GID = this.cbxChlNum.SelectedIndex / mapCount;
            //ControlFactor.GID = this.cbxChlNum.SelectedIndex / mapCount;
            //显示用数据包赋值
            //ProtectFactor.command_update_en = 0x00;
            //ProtectFactor.protect_update_en = 0xff;
            //for (int i = 0; i < 12; i++)
            //{
            //    if (i < 6)
            //    {
            //        ProtectFactor.displayCaliFactor[i].range = (float)calibrates.list[ProtectFactor.CID][FactorName.CurFactor][i].UpperLimit;
            //        ProtectFactor.displayCaliFactor[i].k = (float)calibrates.list[ProtectFactor.CID][FactorName.CurFactor][i].Showk;
            //        ProtectFactor.displayCaliFactor[i].b = (float)calibrates.list[ProtectFactor.CID][FactorName.CurFactor][i].Showb;
            //    }
            //    else
            //    {
            //        ProtectFactor.displayCaliFactor[i].range = (float)calibrates.list[ProtectFactor.CID][FactorName.VolFactor][i - 6].UpperLimit;
            //        ProtectFactor.displayCaliFactor[i].k = (float)calibrates.list[ProtectFactor.CID][FactorName.VolFactor][i - 6].Showk;
            //        ProtectFactor.displayCaliFactor[i].b = (float)calibrates.list[ProtectFactor.CID][FactorName.VolFactor][i - 6].Showb;
            //    }
            //}
            for (int i = 0; i < 6; i++)
            {
                 CurrentFactor.displayCaliFactor[i].range = (float)calibrates.list[CurrentFactor.CID][FactorName.CurFactor][i].UpperLimit;
                 CurrentFactor.displayCaliFactor[i].k = (float)calibrates.list[CurrentFactor.CID][FactorName.CurFactor][i].Showk;
                 CurrentFactor.displayCaliFactor[i].b = (float)calibrates.list[CurrentFactor.CID][FactorName.CurFactor][i].Showb;
                 VoltageFactor.displayCaliFactor[i].range = (float)calibrates.list[VoltageFactor.CID][FactorName.VolFactor][i].UpperLimit;
                 VoltageFactor.displayCaliFactor[i].k = (float)calibrates.list[VoltageFactor.CID][FactorName.VolFactor][i].Showk;
                 VoltageFactor.displayCaliFactor[i].b = (float)calibrates.list[VoltageFactor.CID][FactorName.VolFactor][i].Showb;
                 CurrentFactor.controlCaliFactor[i].range = (float)calibrates.list[CurrentFactor.CID][FactorName.CurFactor][i].UpperLimit;
                 CurrentFactor.controlCaliFactor[i].k = (float)calibrates.list[CurrentFactor.CID][FactorName.CurFactor][i].Controlk;
                 CurrentFactor.controlCaliFactor[i].b = (float)calibrates.list[CurrentFactor.CID][FactorName.CurFactor][i].Controlb;
                 VoltageFactor.controlCaliFactor[i].range = (float)calibrates.list[VoltageFactor.CID][FactorName.VolFactor][i].UpperLimit;
                 VoltageFactor.controlCaliFactor[i].k = (float)calibrates.list[VoltageFactor.CID][FactorName.VolFactor][i].Controlk;
                 VoltageFactor.controlCaliFactor[i].b = (float)calibrates.list[VoltageFactor.CID][FactorName.VolFactor][i].Controlb;
            }
            byte[] sendCurrent = CurrentFactor.Command();
            //lock (StartListen.synObj)
            //{
            //    StartListen.queSend.Enqueue(new SendInfo(sendCurrent, StartListen.clientDic[dev_ip]));
            //}
            //byte[] sendVoltage = VoltageFactor.Command();
            //lock (StartListen.synObj)
            //{
            //    StartListen.queSend.Enqueue(new SendInfo(sendVoltage, StartListen.clientDic[dev_ip]));
            //}
            //byte[] sendShow = ProtectFactor.Command();
            //lock (StartListen.synObj)
            //{
            //    StartListen.queSend.Enqueue(new SendInfo(sendShow, StartListen.clientDic[dev_ip]));
            //}
            //Thread.Sleep(10);
            //控制用校正因子包赋值
            //ControlFactor.command_update_en = 0xff;
            //ControlFactor.protect_update_en = 0x00;
            //for (int i = 0; i < 12; i++)
            //{
            //    if (i < 6)
            //    {
            //        ControlFactor.controlCaliFactor[i].range = (float)calibrates.list[ControlFactor.CID][FactorName.CurFactor][i].UpperLimit;
            //        ControlFactor.controlCaliFactor[i].k = (float)calibrates.list[ControlFactor.CID][FactorName.CurFactor][i].Controlk;
            //        ControlFactor.controlCaliFactor[i].b = (float)calibrates.list[ControlFactor.CID][FactorName.CurFactor][i].Controlb;

            //    }
            //    else
            //    {
            //        ControlFactor.controlCaliFactor[i].range = (float)calibrates.list[ControlFactor.CID][FactorName.VolFactor][i - 6].UpperLimit;
            //        ControlFactor.controlCaliFactor[i].k = (float)calibrates.list[ControlFactor.CID][FactorName.VolFactor][i - 6].Controlk;
            //        ControlFactor.controlCaliFactor[i].b = (float)calibrates.list[ControlFactor.CID][FactorName.VolFactor][i - 6].Controlb;
            //    }
            //}
            //byte[] sendControl = ControlFactor.Command();
            //lock (StartListen.synObj)
            //{
            //    StartListen.queSend.Enqueue(new SendInfo(sendControl, StartListen.clientDic[dev_ip]));
            //}
            MessageBox.Show("校正因子下发成功");
        }
        /// <summary>
        /// 读电压因子按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReadVolFactor_Click(object sender, EventArgs e)
        {
            try
            {
                factorName = FactorName.VolFactor;
                factorList = curChannelCalibrate[factorName];
                UpdateCalibrateGridView();
            }
            catch (Exception ex)
            {
                MessageBox.Show("未选择校正因子文件！");
                Console.WriteLine(ex.StackTrace + ex.Message);
            }
        }
        /// <summary>
        /// 读电流因子
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReadCurrFactor_Click(object sender, EventArgs e)
        {
            try
            {
                factorName = FactorName.CurFactor;
                factorList = curChannelCalibrate[factorName];
                UpdateCalibrateGridView();
            }
            catch (Exception ex)
            {
                MessageBox.Show("未选择校正因子文件！");
                Console.WriteLine(ex.StackTrace + ex.Message);
            }
        }
        /// <summary>
        /// 控制校准按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnControlCal_Click(object sender, EventArgs e)
        {
            //获取数据源
            GetSourceData();
            if (factorList!=null)
            {
                if (gvCalibrate.FocusedRowHandle>=0)
                {
                    //计算控制因子
                    calCalibrate.CalCalibrateControl(factorList[gvCalibrate.FocusedRowHandle], sourceData1, sourceData2);
                }
            }
            //更新校准因子表格
            UpdateCalibrateGridView();
        }
        /// <summary>
        /// 更新校准信息表
        /// </summary>
        private void UpdateCalibrateGridView()
        {
            int currentFocusRow = gvCalibrate.FocusedRowHandle;
            calibrateDataDt.Clear();
            if (factorList != null)
            {
                for (int i = 0; i < factorList.list.Count; i++)
                {
                    DataRow dr = calibrateDataDt.NewRow();
                    dr["upperLimit"] = ((Factor)factorList.list[i]).UpperLimit;
                    dr["lowerLimit"] = ((Factor)factorList.list[i]).LowerLimit;
                    dr["controlk"] = ((Factor)factorList.list[i]).Controlk;
                    dr["controlb"] = ((Factor)factorList.list[i]).Controlb;
                    dr["showk"] = ((Factor)factorList.list[i]).Showk;
                    dr["showb"] = ((Factor)factorList.list[i]).Showb;
                    calibrateDataDt.Rows.Add(dr);
                }
            }
            gvCalibrate.FocusedRowHandle = currentFocusRow;
        }
        /// <summary>
        /// 计算框中获取数据源的方法
        /// </summary>
        private void GetSourceData()
        {
            sourceData1 = new CalibrateSourceData((double)nudFirstSet.Value, (double)nudFirstShow.Value, (double)nudFirstMeasure.Value);
            sourceData2 = new CalibrateSourceData((double)nudSecondSet.Value, (double)nudSecondShow.Value, (double)nudSecondMeasure.Value);
        }
        /// <summary>
        /// 显示校准按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnShowCal_Click(object sender, EventArgs e)
        {
            GetSourceData();
            if (factorList != null)
            {
                if (gvCalibrate.FocusedRowHandle >= 0)
                {
                    //计算显示因子
                    calCalibrate.CalCalibrateShow(factorList[gvCalibrate.FocusedRowHandle], sourceData1, sourceData2);
                }
            }
            UpdateCalibrateGridView();
        }
        /// <summary>
        /// 选择校准通道号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rgChlIndex_SelectedIndexChanged(object sender, EventArgs e)
        {
            caliCIndx = rgChlIndex.SelectedIndex;
            curChannelCalibrate = calibrates.list[caliCIndx];
            factorList = curChannelCalibrate[factorName];
            UpdateCalibrateGridView();
        }
        /// <summary>
        /// 校正因子界面初始化方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CorrectionFactorPage_Load(object sender, EventArgs e)
        {
            try
            {               
                //反序列化xml到calibrates列表
                calibrates = XmlManager.XmlDeSeria<ChannelCalibrates>(fileName);
                InitGrid();
                factorName = FactorName.VolFactor;
                curChannelCalibrate = calibrates.list[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show("校正因子文件格式不正确！");
                this.Close();
                Console.WriteLine(ex.StackTrace + ex.Message);
            }
            try
            {
                this.cbxChlNum.SelectedIndex = 0;//默认选择第一通道
            }
            catch (Exception ex)
            {
                MessageBox.Show("未进行通道映射！");
                Console.WriteLine(ex.StackTrace + ex.Message);
            }
            ResourceCulture.SetCurrentCulture(IndexPage.language);
            this.SetResourceCulture();
        }
        /// <summary>
        /// 初始化GridContron
        /// </summary>
        private void InitGrid()
        {
            calibrateDataDt.Columns.Add(new DataColumn("upperLimit", typeof(double)));
            calibrateDataDt.Columns.Add(new DataColumn("lowerLimit", typeof(double)));
            calibrateDataDt.Columns.Add(new DataColumn("controlk", typeof(double)));
            calibrateDataDt.Columns.Add(new DataColumn("controlb", typeof(double)));
            calibrateDataDt.Columns.Add(new DataColumn("showk", typeof(double)));
            calibrateDataDt.Columns.Add(new DataColumn("showb", typeof(double)));

            gvCalibrate.Columns[0].FieldName = "upperLimit";
            gvCalibrate.Columns[1].FieldName = "lowerLimit";
            gvCalibrate.Columns[2].FieldName = "controlk";
            gvCalibrate.Columns[3].FieldName = "controlb";
            gvCalibrate.Columns[4].FieldName = "showk";
            gvCalibrate.Columns[5].FieldName = "showb";

            gcCalibrate.DataSource = calibrateDataDt;

        }
        /// <summary>
        /// 增加一行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCalibrateDataAdd_Click(object sender, EventArgs e)
        {
            try
            {
                Factor item = new Factor() { Controlk = 1, Showk = 1 };
                HuaCheng.Controller.ListControl.AddItem(factorList.list, item, UpdateCalibrateGridView);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
            }
        }
        //删除一行
        private void btnCalibrateDataDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("是否删除？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    HuaCheng.Controller.ListControl.DeleteItem(factorList.list, UpdateCalibrateGridView, gvCalibrate);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                MessageBox.Show(ex.ToString());
            }
        }
        //上移
        private void btnCalibrateDataUp_Click(object sender, EventArgs e)
        {
            try
            {
                HuaCheng.Controller.ListControl.MoveUpList(factorList.list, UpdateCalibrateGridView, gvCalibrate);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
            }
        }
        //下移
        private void btnCalibrateDataDown_Click(object sender, EventArgs e)
        {
            try
            {
                HuaCheng.Controller.ListControl.MoveDownList(factorList.list, UpdateCalibrateGridView, gvCalibrate);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
            }
        }
        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCalibrateDataSave_Click(object sender, EventArgs e)
        {
            sfdSave.Filter = "校正因子文件|*.xml|All|*.*";
            sfdSave.RestoreDirectory = true;
            if (sfdSave.ShowDialog() == DialogResult.OK)
            {
                SaveData();
                XmlManager.XmlSeria<ChannelCalibrates>(sfdSave.FileName, calibrates);//设备列表对象序列化XML
            }
        }
        private void SaveData()
        {
            for (int i = 0; i < gvCalibrate.RowCount - 1; i++)
            {
                var item = (Factor)factorList[i];
                item.UpperLimit = (double)gvCalibrate.GetRowCellValue(i, "upperLimit");
                item.LowerLimit = (double)gvCalibrate.GetRowCellValue(i, "lowerLimit");
                item.Controlk = (double)gvCalibrate.GetRowCellValue(i, "controlk");
                item.Controlb = (double)gvCalibrate.GetRowCellValue(i, "controlb");
                item.Showk = (double)gvCalibrate.GetRowCellValue(i, "showk");
                item.Showb = (double)gvCalibrate.GetRowCellValue(i, "showb");
            }
        }
        //序列化包含所有通道校准因子的ChannelCalibrates列表
        public void SaveDevCalibrateInfo()
        {
            XmlManager.XmlSeria<ChannelCalibrates>(XmlManager.NewDevCalibraPath, calibrates);//设备列表对象序列化XML
        }
        #region 国际化
        /// <summary>
        /// 为当前页面内所有控件设置文本语种
        /// </summary>
        private void SetResourceCulture()
        {
            this.Text = ResourceCulture.GetString("CorrectText");
            this.gcChlNum.Text = ResourceCulture.GetString("CorrectionChlID");
            this.btnReadCurrFactor.Text = ResourceCulture.GetString("ReadCurrFactor");
            this.btnReadVolFactor.Text = ResourceCulture.GetString("ReadVolFactor");
            this.btnCalibrateDataAdd.Text = ResourceCulture.GetString("Add2");
            this.btnCalibrateDataDel.Text = ResourceCulture.GetString("Delete");
            this.btnCalibrateDataUp.Text = ResourceCulture.GetString("Up");
            this.btnCalibrateDataDown.Text = ResourceCulture.GetString("Down");
            this.btnCalibrateDataSave.Text = ResourceCulture.GetString("Save2");
            this.btnExit.Text = ResourceCulture.GetString("Exit");
            this.gcLoad.Text = ResourceCulture.GetString("CorrectionLoad");
            this.btnLoad.Text = ResourceCulture.GetString("Load");
            this.gcCalculate.Text = ResourceCulture.GetString("Calculate");
            this.lblFirstData.Text = ResourceCulture.GetString("FirstGroupData");
            this.lblSecondData.Text = ResourceCulture.GetString("SecondGroupData");
            this.lblFirstSet.Text = ResourceCulture.GetString("SetValue");
            this.lblSecondSet.Text = ResourceCulture.GetString("SetValue");
            this.lblFirstShow.Text = ResourceCulture.GetString("ShowValue");
            this.lblSecondShow.Text = ResourceCulture.GetString("ShowValue");
            this.lblFirstMeasure.Text = ResourceCulture.GetString("MeasuredValue");
            this.lblSecondMeasure.Text = ResourceCulture.GetString("MeasuredValue");
            this.btnControlCal.Text = ResourceCulture.GetString("CalibrationControl");
            this.btnShowCal.Text = ResourceCulture.GetString("ShowControl");
            this.gcMax.Caption = ResourceCulture.GetString("UpperLimit");
            this.gcMin.Caption = ResourceCulture.GetString("LowerLimit");
            this.gcControlk.Caption = ResourceCulture.GetString("ControlK");
            this.gcControlb.Caption = ResourceCulture.GetString("ControlB");
            this.gcShowk.Caption = ResourceCulture.GetString("ShowK");
            this.gcShowb.Caption = ResourceCulture.GetString("ShowB");
        }
        #endregion
    }
}
